package com.lebang.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lebang.common.utils.OkHttpUtil;
import com.lebang.component.RedisClient;
import com.lebang.entity.RequestHeaders;
import com.lebang.mapper.LbbMemberMapper;
import com.lebang.model.back.ImeiRegister;
import com.lebang.model.back.KsapiModel;
import com.lebang.model.back.OceanEngine;
import com.lebang.model.back.QqapiModel;
import com.lebang.service.mongodb.ImeiRegisterMongodb;
import com.lebang.service.mongodb.KsApiModelMongodb;
import com.lebang.service.mongodb.OceanEngineMongodb;
import com.lebang.service.mongodb.QqApiModelMongodb;
import com.lebangweb.common.UUIDUtil;
import com.lebangweb.encrypt.MessageDigestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.net.URLDecoder;
import java.time.LocalDateTime;
import java.util.Optional;

/**
 * @Author: hwq
 * @Date: 2020/5/8 10:43
 * @Version 1.0
 */
@Service
@Slf4j
public class OceanEngineService {
    @Value("${info.tenxun.access_token}")
    private String accessToken;
    @Value("${info.tenxun.account_id}")
    private String account_id;
    @Value("${info.tenxun.user_action_set_id}")
    private String user_action_set_id;
    @Autowired
    private OceanEngineMongodb oceanEngineMongodb;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private ImeiRegisterMongodb imeiRegisterMongodb;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private QqApiModelMongodb qqApiModelMongodb;
    @Autowired
    private KsApiModelMongodb ksApiModelMongodb;
    private static final String CALL_BACK_URL = "https://ad.oceanengine.com/track/activate?";
    private static final String TX_QQ_URL = "https://api.e.qq.com/v1.1/user_actions/add?access_token={access_token}&timestamp={timestamp}&nonce={nonce}";
    private static final String ACTIONS = "[{\"action_time\":\"<action_timestamp>\",\"user_id\":{\"hash_imei\":\"<MD5_hash_imei>\",\"oaid\":\"<oaid>\"},\"action_type\":\"ACTIVATE_APP\"}]\n";
    private static final String KS_CALL_BACK_URL = "http://ad.partner.gifshow.com/track/activate?";

    @Async
    public void check(RequestHeaders requestHeaders, int i) {
        String uuid = UUIDUtil.M();
        try {
            boolean lock = redisClient.tryGetDistributedLock("lick:imei:oceanengine:" + requestHeaders.getImei(), uuid, 500);
            if (!lock) {
                return;
            }
            if (requestHeaders.getAppStore().startsWith("csj")) {
                Optional<OceanEngine> result = this.exits(requestHeaders, i);
                if (!result.isPresent()) {
                    return;
                }

                OkHttpUtil.getRequest(CALL_BACK_URL +
                        "callback=" + result.get().getCallback() +
                        "&muid=" + result.get().getImei() +
                        "&event_type=" + i +
                        "&conv_time=" + System.currentTimeMillis() +
                        // "&muid="+ MessageDigestUtil.encryptMD5(requestHeaders.getImei().getBytes())+
                        "&os=0");
                result.get().setStatus(1);
                oceanEngineMongodb.save(result.get());
                log.info("巨量回传激活");
            }

            if (requestHeaders.getAppStore().startsWith("gdt")) {
                Optional<QqapiModel> result = this.exitsByTx(requestHeaders);
                if (!result.isPresent()) {
                    return;
                }
                String imeiMd5 = MessageDigestUtil.encryptMD5(requestHeaders.getImei().toLowerCase().getBytes());
                String mac = MessageDigestUtil.encryptMD5(requestHeaders.getMacAddr().toUpperCase().replace(":", "").getBytes());
                String request = "{\"account_id\":\"" + account_id + "\"," +
                        "\"actions\":[{\"action_time\":" + System.currentTimeMillis() / 1000 + "," +
                        "\"action_type\":\"ACTIVATE_APP\"," +
                        "\"trace\":{\"clcik_id\":\"" + result.get().getClick_id() + "\"}," +
                        "\"user_id\":{\"hash_imei\":\"" + imeiMd5 + "\"," +
                        "\"hash_mac\":\"" + mac + "\"," +
                        "\"oaid\":\"" + requestHeaders.getOaid() + "\"}}]," +
                        "\"user_action_set_id\":\"" + user_action_set_id + "\"}";
                String str = TX_QQ_URL
                        .replace("{access_token}", accessToken)
                        .replace("{timestamp}", String.valueOf(System.currentTimeMillis() / 1000))
                        .replace("{nonce}", UUIDUtil.L());
                System.out.println(JSON.toJSONString(request));
                System.out.println(OkHttpUtil.postRequestJson(str, request));
                ;
                result.get().setStatus(1);
                qqApiModelMongodb.save(result.get());
                log.info("gdt回传激活");
            }

            if (requestHeaders.getAppStore().startsWith("kuaishou")) {
                Optional<KsapiModel> result = this.exitsByKs(requestHeaders, i);
                if (!result.isPresent()) {
                    return;
                }

                JSONObject jsonObject = OkHttpUtil.getRequest(URLDecoder.decode(result.get().getCallback(), "UTF-8") +
                        "&event_type=1" +
                        "&event_time=" + System.currentTimeMillis()
                );
                System.out.println(URLDecoder.decode(result.get().getCallback(), "UTF-8") +
                        "&event_type=1" +
                        "&event_time=" + System.currentTimeMillis());
System.out.println(jsonObject);
                if (jsonObject.getIntValue("result") == 1) {
                    result.get().setStatus(1);
                    ksApiModelMongodb.save(result.get());
                    log.info("快手回传激活");
                } else {
                    log.info("快手回传激活失败");
                }


            }


        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public Optional<OceanEngine> exits(RequestHeaders requestHeaders, int i) {
        try {
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime star = now.minusDays(7);
            Sort sort = Sort.by(Sort.Direction.DESC, "creatTime");
            String andid = MessageDigestUtil.encryptMD5(requestHeaders.getAndroid_id().getBytes());
            Query query = new Query();
            Criteria criteria = new Criteria();
            criteria.and("creatTime").gte(star).lte(now);
            criteria.and("os").is("0");
            criteria.and("status").is(i);
            criteria.orOperator(
                    Criteria.where("imei")
                            .is(MessageDigestUtil.encryptMD5(requestHeaders.getImei().getBytes())),
                    Criteria.where("mac")
                            .is(MessageDigestUtil.encryptMD5(requestHeaders.getMacAddr().toUpperCase().replace(":", "").getBytes())),
                    Criteria.where("android_id")
                            .is(andid),
                    Criteria.where("oaid")
                            .is(requestHeaders.getOaid()));
            query.addCriteria(criteria);
            query.with(sort);
            OceanEngine mongoVehicleUploadLogs = mongoTemplate.findOne(query, OceanEngine.class);
            return Optional.ofNullable(mongoVehicleUploadLogs);
        } catch (Exception e) {
            return Optional.empty();
        }


    }

    public Optional<QqapiModel> exitsByTx(RequestHeaders requestHeaders) {
        try {
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime star = now.minusDays(7);
            Sort sort = Sort.by(Sort.Direction.DESC, "creatTime");
            String andid = MessageDigestUtil.encryptMD5(requestHeaders.getAndroid_id().getBytes());

            Query query = new Query();
            Criteria criteria = new Criteria();
            criteria.and("creatTime").gte(star).lte(now);
            criteria.and("status").is(0);
            criteria.orOperator(
                    Criteria.where("muid")
                            .is(MessageDigestUtil.encryptMD5(requestHeaders.getImei().getBytes())),
                    Criteria.where("mac")
                            .is(MessageDigestUtil.encryptMD5(requestHeaders.getMacAddr().toUpperCase().replace(":", "").getBytes())),
                    Criteria.where("oaid")
                            .is(requestHeaders.getOaid()));
            query.addCriteria(criteria);
            query.with(sort);
            QqapiModel mongoVehicleUploadLogs = mongoTemplate.findOne(query, QqapiModel.class);
            return Optional.ofNullable(mongoVehicleUploadLogs);
        } catch (Exception e) {
            return Optional.empty();
        }


    }


    public Optional<KsapiModel> exitsByKs(RequestHeaders requestHeaders, int i) {
        try {
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime star = now.minusDays(7);
            Sort sort = Sort.by(Sort.Direction.DESC, "creatTime");
            String andid = MessageDigestUtil.encryptMD5(requestHeaders.getAndroid_id().getBytes());
            Query query = new Query();
            Criteria criteria = new Criteria();
            criteria.and("creatTime").gte(star).lte(now);
            criteria.and("status").is(i);
            criteria.orOperator(
                    Criteria.where("imei")
                            .is(MessageDigestUtil.encryptMD5(requestHeaders.getImei().getBytes())),
                    Criteria.where("mac")
                            .is(MessageDigestUtil.encryptMD5(requestHeaders.getMacAddr().replace(":", "").getBytes())),
                    Criteria.where("androidid")
                            .is(andid),
                    Criteria.where("oaid")
                            .is(requestHeaders.getOaid()));
            query.addCriteria(criteria);
            query.with(sort);
            KsapiModel ksapiModel = mongoTemplate.findOne(query, KsapiModel.class);
            return Optional.ofNullable(ksapiModel);
        } catch (Exception e) {
            return Optional.empty();
        }


    }


    public void addImei(ImeiRegister requestHeaders, RequestHeaders headers) {
        if (!imeiRegisterMongodb.existsById(requestHeaders.getImei())) {
            //新增设备
            //           LbbMember lbbMember = lbbMemberMapper.selectById(headers.getUserid());
//            if(lbbMember==null){
            imeiRegisterMongodb.save(requestHeaders);
            this.check(headers, 0);
//            }


        }
    }


    /**
     * 检查注册
     *
     * @param requestHeaders
     * @param i
     */
    public void checkResinTear(RequestHeaders requestHeaders, int i) {
        String uuid = UUIDUtil.M();
        try {
            boolean lock = redisClient.tryGetDistributedLock("lick:imei:oceanengine:" + requestHeaders.getImei(), uuid, 500);
            if (!lock) {
                return;
            }
            if (requestHeaders.getAppStore().startsWith("csj")) {
                Optional<OceanEngine> result = this.exits(requestHeaders, i);
                if (!result.isPresent()) {
                    return;
                }

//                OkHttpUtil.getRequest(CALL_BACK_URL +
//                        "callback=" + result.get().getCallback() +
//                        "&muid=" + result.get().getImei() +
//                        "&event_type=" + i +
//                        "&conv_time=" + System.currentTimeMillis() +
//                        // "&muid="+ MessageDigestUtil.encryptMD5(requestHeaders.getImei().getBytes())+
//                        "&os=0");
                result.get().setStatus(2);
                oceanEngineMongodb.save(result.get());
                log.info("巨量回传激活");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
